package com.mes.loco.aps.server.controller.sfc;

import com.alibaba.fastjson.JSON;
import com.iplant.aps.controller.BaseController;
import com.iplant.aps.service.SFCService;
// import com.iplant.aps.service.po.OutResult;
import com.iplant.aps.service.po.ServiceResult;
import com.iplant.aps.service.po.bms.BMSEmployee;
import com.iplant.aps.service.po.bpm.BPMTaskBase;
import com.iplant.aps.service.po.sap.SAPResult;
import com.iplant.aps.service.po.sfc.SFCQualityLossBPM;
import com.iplant.aps.service.utils.CloneTool;
import com.iplant.aps.service.utils.StringUtils;
import com.iplant.aps.utils.RetCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 质量损失(流程引擎版)
 *
 * @author PengYouWang
 * 2022-8-26 14:42:56
 */
@RestController
@RequestMapping("/api/SFCQualityLossBPM")
public class SFCQualityLossBPMController extends BaseController {
    private static final Logger logger = LoggerFactory.getLogger(SFCQualityLossBPMController.class);

    final SFCService wSFCService;

    public SFCQualityLossBPMController(SFCService wSFCService) {
        this.wSFCService = wSFCService;
    }

    /**
     * 查历史记录
     */
    @GetMapping("/History")
    public Object History(HttpServletRequest request) {
        Object wResult = new Object();
        try {
            if (CheckCookieEmpty(request)) {
                wResult = GetResult(RetCode.SERVER_CODE_UNLOGIN, "");
                return wResult;
            }

            BMSEmployee wLoginUser = GetSession(request);

            // 获取参数
            String wCode = StringUtils.parseString(request.getParameter("Code"));
            int wUpFlowID = StringUtils.parseInt(request.getParameter("UpFlowID"));
            // int wFollowerID = StringUtils.parseInt(request.getParameter("FollowerID"));
            int wOrderID = StringUtils.parseInt(request.getParameter("OrderID"));
            int wPartID = StringUtils.parseInt(request.getParameter("PartID"));
            int wPartPointID = StringUtils.parseInt(request.getParameter("PartPointID"));
            int wSAPStatus = StringUtils.parseInt(request.getParameter("wSAPStatus"));
            Calendar wStartTime = StringUtils.parseCalendar(request.getParameter("StartTime"));
            Calendar wEndTime = StringUtils.parseCalendar(request.getParameter("EndTime"));

            ServiceResult<List<SFCQualityLossBPM>> wServiceResult = wSFCService.SFC_QueryQualityLossBPMHistory(
                    wLoginUser,
                    -1, wCode, wUpFlowID, wOrderID, wPartID, wPartPointID, wSAPStatus, wStartTime, wEndTime);

            if (StringUtils.isEmpty(wServiceResult.FaultCode)) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "", wServiceResult.Result, null);
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServiceResult.FaultCode);
            }
        } catch (Exception ex) {
            logger.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString(), null, null);
        }
        return wResult;
    }

    /**
     * 人员获取任务
     */
    @GetMapping("/EmployeeAll")
    public Object EmployeeAll(HttpServletRequest request) {
        Object wResult = new Object();
        try {
            if (CheckCookieEmpty(request)) {
                wResult = GetResult(RetCode.SERVER_CODE_UNLOGIN, "");
                return wResult;
            }

            BMSEmployee wLoginUser = GetSession(request);

            // 获取参数
            int wTagTypes = StringUtils.parseInt(request.getParameter("TagTypes"));
            Calendar wStartTime = StringUtils.parseCalendar(request.getParameter("StartTime"));
            Calendar wEndTime = StringUtils.parseCalendar(request.getParameter("EndTime"));

            ServiceResult<List<BPMTaskBase>> wServiceResult = wSFCService.SFC_QueryQualityLossBPMEmployeeAll(wLoginUser,
                    wTagTypes, wStartTime, wEndTime);

            if (StringUtils.isEmpty(wServiceResult.FaultCode)) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "", wServiceResult.Result, null);
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServiceResult.FaultCode);
            }
        } catch (Exception ex) {
            logger.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString(), null, null);
        }
        return wResult;
    }

    /**
     * 获取待办、已办、发起任务(试运申请)
     */
    @GetMapping("/EmployeeAllNew")
    public Object EmployeeAllNew(HttpServletRequest request) {
        Object wResult = new Object();
        try {
            if (CheckCookieEmpty(request)) {
                wResult = GetResult(RetCode.SERVER_CODE_UNLOGIN, "");
                return wResult;
            }

            BMSEmployee wLoginUser = GetSession(request);

            // 获取参数
            Calendar wStartTime = StringUtils.parseCalendar(request.getParameter("StartTime"));
            Calendar wEndTime = StringUtils.parseCalendar(request.getParameter("EndTime"));

            int wOrderID = StringUtils.parseInt(request.getParameter("OrderID"));
            int wPartID = StringUtils.parseInt(request.getParameter("PartID"));
            int wStatus = StringUtils.parseInt(request.getParameter("Status"));

            ServiceResult<List<SFCQualityLossBPM>> wServiceResult = wSFCService
                    .SFC_QuerySFCQualityLossBPMEmployeeAllNew(wLoginUser, wStartTime, wEndTime, wOrderID, wPartID,
                            wStatus);

            if (StringUtils.isEmpty(wServiceResult.FaultCode)) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "", wServiceResult.Result, null);
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServiceResult.FaultCode);
            }
        } catch (Exception ex) {
            logger.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString(), null, null);
        }
        return wResult;
    }

    /**
     * 获取待办、已办、发起 质量损失评审任务
     */
    @GetMapping("/EmployeeAllWeb")
    public Object EmployeeAllWeb(HttpServletRequest request) {
        Object wResult;
        try {
            if (CheckCookieEmpty(request)) {
                wResult = GetResult(RetCode.SERVER_CODE_UNLOGIN, "");
                return wResult;
            }

            BMSEmployee wLoginUser = GetSession(request);

            Calendar wStartTime = StringUtils.parseCalendar(request.getParameter("StartTime"));
            Calendar wEndTime = StringUtils.parseCalendar(request.getParameter("EndTime"));

            int wOrderID = StringUtils.parseInt(request.getParameter("OrderID"));
            int wPartID = StringUtils.parseInt(request.getParameter("PartID"));
            int wStatus = StringUtils.parseInt(request.getParameter("Status"));
            int wSAPStatus = StringUtils.parseInt(request.getParameter("SAPStatus"));

            String wMaterial = StringUtils.parseString(request.getParameter("Material"));
            String wCode = StringUtils.parseString(request.getParameter("Code"));

            ServiceResult<List<SFCQualityLossBPM>> wServiceResult = wSFCService
                    .SFC_QueryQualityLossBPMListEmployeeAllWeb(wLoginUser, wOrderID,
                            wPartID, wStatus, wStartTime, wEndTime, wMaterial, wCode, wSAPStatus);

            //处理状态文本重复问题
            SAPResult sapResult;
            List<String> strings;
            for (SFCQualityLossBPM wItem : wServiceResult.Result) {
                if (wItem.SAPStatusText.contains("配置标准工序")) {
                    sapResult = JSON.parseObject(wItem.SAPStatusText, SAPResult.class);
                    strings = StringUtils.parseList(sapResult.msg.split("\\|"));
                    strings = strings.stream().distinct().collect(Collectors.toList());
                    sapResult.msg = StringUtils.Join("|", strings);
                    wItem.SAPStatusText = JSON.toJSONString(sapResult);
                }
            }

            if (StringUtils.isEmpty(wServiceResult.FaultCode)) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "", wServiceResult.Result, null);
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServiceResult.FaultCode);
            }
        } catch (Exception ex) {
            logger.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString(), null, null);
        }
        return wResult;
    }

    /**
     * 查单条
     */
    @GetMapping("/Info")
    public Object Info(HttpServletRequest request) {
        Object wResult = new Object();
        try {
            if (CheckCookieEmpty(request)) {
                wResult = GetResult(RetCode.SERVER_CODE_UNLOGIN, "");
                return wResult;
            }

            BMSEmployee wLoginUser = GetSession(request);

            // 获取参数
            int wID = StringUtils.parseInt(request.getParameter("ID"));

            ServiceResult<SFCQualityLossBPM> wServiceResult = wSFCService.SFC_GetQualityLossBPM(wLoginUser, wID);

            if (StringUtils.isEmpty(wServiceResult.FaultCode)) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "", null, wServiceResult.Result);
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServiceResult.FaultCode);
            }
        } catch (Exception ex) {
            logger.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString(), null, null);
        }
        return wResult;
    }

    /**
     * 更新任务
     */
    @PostMapping("/Update")
    public Object Update(HttpServletRequest request, @RequestBody Map<String, Object> wParam) {
        Map<String, Object> wResult = new HashMap<>();
        try {
            if (CheckCookieEmpty(request)) {
                wResult = GetResult(RetCode.SERVER_CODE_UNLOGIN, "");
                return wResult;
            }

            BMSEmployee wLoginUser = GetSession(request);
            // OutResult<Integer> wErrorCode = new OutResult<>(0);

            // 获取参数
            SFCQualityLossBPM wSFCQualityLossBPM = CloneTool.Clone(wParam.get("data"), SFCQualityLossBPM.class);
            if (wSFCQualityLossBPM == null || wSFCQualityLossBPM.ID <= 0) {
                return GetResult(RetCode.SERVER_CODE_ERR, RetCode.SERVER_RST_ERROR_OUT);
            }

            ServiceResult<Integer> wServiceResult = wSFCService.SFC_UpdateQualityLossBPM(wLoginUser,
                    wSFCQualityLossBPM);

            if (StringUtils.isEmpty(wServiceResult.FaultCode)) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "", null, wServiceResult.Result);
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServiceResult.FaultCode);
            }
        } catch (Exception ex) {
            logger.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString(), null, null);
        }
        return wResult;
    }

    /**
     * 重新推送质量损失
     */
    @PostMapping("/ReSend")
    public Object ReSend(HttpServletRequest request, @RequestBody Map<String, Object> wParam) {
        Map<String, Object> wResult = new HashMap<String, Object>();
        try {
            if (CheckCookieEmpty(request)) {
                wResult = GetResult(RetCode.SERVER_CODE_UNLOGIN, "");
                return wResult;
            }

            BMSEmployee wLoginUser = GetSession(request);

            // 获取参数
            int wSFCQualityLossID = StringUtils.parseInt(wParam.get("SFCQualityLossID"));
            if (wSFCQualityLossID <= 0) {
                return GetResult(RetCode.SERVER_CODE_ERR, RetCode.SERVER_RST_ERROR_OUT);
            }

            ServiceResult<Integer> wServiceResult = wSFCService.SFC_ReSendQualityLoss(wLoginUser, wSFCQualityLossID);

            if (StringUtils.isEmpty(wServiceResult.FaultCode)) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "", null, wServiceResult.Result);
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServiceResult.FaultCode);
            }
        } catch (Exception ex) {
            logger.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString(), null, null);
        }
        return wResult;
    }

    /**
     * 导出
     */
    @GetMapping("/Export")
    public Object Export(HttpServletRequest request) {
        Object wResult = new Object();
        try {
            if (CheckCookieEmpty(request)) {
                wResult = GetResult(RetCode.SERVER_CODE_UNLOGIN, "");
                return wResult;
            }

            BMSEmployee wLoginUser = GetSession(request);

            // 获取参数
            Calendar wStartTime = StringUtils.parseCalendar(request.getParameter("StartTime"));
            Calendar wEndTime = StringUtils.parseCalendar(request.getParameter("EndTime"));

            ServiceResult<String> wServiceResult = wSFCService.WMS_ExportQualityLoss(wLoginUser, wStartTime, wEndTime);

            if (StringUtils.isEmpty(wServiceResult.FaultCode)) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "", null, wServiceResult.Result);
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServiceResult.FaultCode);
            }
        } catch (Exception ex) {
            logger.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString(), null, null);
        }
        return wResult;
    }
}
